/**
 * @author jjisaac
 */
var miniPvOpen = false;
var DEFAULT_GEN_LINK = 'images/';
var DEFAULT_SEC_LINK = 'images/';
var DEF_TAG_MV;
var ias = null;
var curImg = new Image();
var tgCounter = 1;
var tagSets = [];
var tgNmSt = [];
var usrLst = [{
    text: 'isaac khaguli',
    value: 123001
}, {
    text: 'Nelson Mandela',
    value: 123002
}];
var thImgJson = [{
    id: 1110001,
    name: 'myclasst1.jpg',
    width: 100,
    height: 70,
    url: 'myclass.jpg'
}, {
    id: 1110002,
    name: '1a.jpg',
    width: 57,
    height: 100,
    url: '1.jpg'
}, {
    id: 1110003,
    name: 'thumbMos2.jpg',
    width: 100,
    height: 75,
    url: ''
}, {
    id: 1110004,
    name: 'thumbMos2.jpg',
    width: 100,
    height: 75,
    url: ''
}, {
    id: 1110005,
    name: 'thumbMos2.jpg',
    width: 100,
    height: 75,
    url: ''
}, {
    id: 1110006,
    name: 'thumbMos2.jpg',
    width: 100,
    height: 75,
    url: ''
}, {
    id: 1110007,
    name: 'thumbMos2.jpg',
    width: 100,
    height: 75,
    url: ''
}, {
    id: 1110006,
    name: 'thumbMos2.jpg',
    width: 100,
    height: 75,
    url: ''
}, {
    id: 1110007,
    name: 'thumbMos2.jpg',
    width: 100,
    height: 75,
    url: ''
}, {
    id: 1110006,
    name: 'thumbMos2.jpg',
    width: 100,
    height: 75,
    url: ''
}, {
    id: 1110007,
    name: 'thumbMos2.jpg',
    width: 100,
    height: 75,
    url: ''
}, {
    id: 1110002,
    name: '1a.jpg',
    width: 57,
    height: 100,
    url: '1.jpg'
}, {
    id: 1110007,
    name: 'thumbMos2.jpg',
    width: 100,
    height: 75,
    url: ''
}];
var scrlY = 0;

function setter(){
    if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
        var ffversion = new Number(RegExp.$1) // capture x.x portion and store as a number
        if (ffversion >= 3) {
            DEF_TAG_MV = 0;
        }
        else 
            if (ffversion >= 2) {
                document.write("You're using FF 2.x")
            }
            else 
                if (ffversion >= 1) {
                    document.write("You're using FF 1.x")
                }
    }
    else 
        if (navigator.userAgent.match(/Opera/ig)) {
            DEF_TAG_MV = 0;
        }
        else 
            if (navigator.userAgent.match(/Safari/ig)) {
                DEF_TAG_MV = 0;
            }
            else {
            }
}

function updateTips(t){
    tips.text(t).addClass('ui-state-highlight');
    setTimeout(function(){
        tips.removeClass('ui-state-highlight', 1500);
    }, 500);
}

function checkLength(o, n, min, max){

    if (o.val().length > max || o.val().length < min) {
        o.addClass('ui-state-error');
        updateTips("Length of " + n + " must be between " + min + " and " + max + ".");
        return false;
    }
    else {
        return true;
    }
    
}

function checkRegexp(o, regexp, n){

    if (!(regexp.test(o.val()))) {
        o.addClass('ui-state-error');
        updateTips(n);
        return false;
    }
    else {
        return true;
    }
    
}

function activateTag(){
    $('.tgWin').remove();
    toggleViewBarImg(false, 'Click <br> Image');
    toggleTag(false);
    var tgVBB = $gel('tagViewButtonBar');
    $('#tagViewButtonBar').html('');
    var tagBt = document.createElement('button');
    tagBt.id = 'tgBut';
    $(tagBt).html('Tag');
    $(tagBt).attr('disabled', true);
    tagBt.className = 'tgbutton';
    var tagCancelBt = document.createElement('button');
    tagCancelBt.id = 'tgCancel';
    $(tagCancelBt).html('Cancel');
    tagCancelBt.className = 'tgbutton';
    var tagDeactBt = document.createElement('button');
    tagDeactBt.id = 'tgDeAct';
    $(tagDeactBt).html('Done');
    tagDeactBt.style.marginTop = '30px';
    tagDeactBt.className = 'tgbutton';
    tgVBB.appendChild(tagBt);
    tgVBB.appendChild(brln());
    tgVBB.appendChild(tagCancelBt);
    tgVBB.appendChild(brln());
    tgVBB.appendChild(tagDeactBt);
    
    ias = $('img#svImgld').imgAreaSelect({
        fadeSpeed: 300,
        handles: true,
        instance: true,
        closeButton: 'tgCancel',
        aspectRatio: '1:1',
        onSelectChange: preview,
        deactivateButton: {
            btId: 'tgDeAct',
            callback: activateTags
        },
        activateButton: 'tgAct',
        tagButton: 'tgBut'
    });
    $('#actPnl').css({
        'display': 'none'
    });
    
    ias.imgObj.bind('click', initSelector);
}

function toggleVC(element, stl){
    $('#' + element).uncorner();
    if ($('#' + element).attr('actv') == 'on') {
        $('#' + element).corner();
    }
    else {
        $('#' + element).corner(stl);
    }
}

function appendLdBar(container){
    var loaderBar = ldBar(0, 0);
    document.body.appendChild(loaderBar);
    centerWN(container, loaderBar.id);
}

function ldBar(top, left){
    var ldBarImage = document.createElement('img');
    var ldBarImageDiv = document.createElement('div');
    ldBarImageDiv.className = 'loader';
    ldBarImage.src = 'images/loading_min.gif';
    ldBarImageDiv.appendChild(ldBarImage);
    ldBarImageDiv.appendChild(brln());
    ldBarImageDiv.innerHTML += 'loading';
    ldBarImageDiv.style.top = top + 'px';
    ldBarImageDiv.style.left = left + 'px';
    ldBarImageDiv.id = 'ldBar';
    return ldBarImageDiv;
}

function removeLdBar(){
    $('#ldBar').remove();
}

function loadImage(container, url, callback){
    appendLdBar('imgCont');
    ias != null ? ias.cancelSelection(null, true) : null;
    $('#' + container).html('');
    $(curImg).load(function(){
        //this.style.cssText = 'display: none;';
        this.id = 'svImgld';
        $('#' + container).append(this);
        
        $('#' + container).animate({
            height: $(this).height(),
            "easing": "easeout",
        }, 50, function(){
            //            $(curImg).fadeIn(500);
        });
        removeLdBar();
        togglethView(false);
        $('#tagViewButton').attr('disabled', false);
        callback != null ? callback() : null;
    }).attr('src', url);
}

function buttonDiv(id, inText){
    var btDiv = document.createElement('div');
    btDiv.id = id;
    $(btDiv).html('Text');
}

function brln(){
    return document.createElement('br');
}

function initSelector(e){
    var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;
    selector(this, 100, 100, x, y, false, ias);
    ias.selectOn();
}

function selector(clkEml, width, height, mouseX, mouseY, start, ias){
    var selWidth = width, selHeight = height;
    var x1, x2, y1, y2;
    if (start) {
        x1 = mouseX - (width / 2);
        y1 = mouseY - (height / 2);
    }
    else {
        if ((mouseX < (width / 2)) && (mouseY < (height / 2))) {
            x1 = 5;
            y1 = 5;
            //$('#pValue').append('##Close to left corner top##');
        }
        else 
            if (($(clkEml).width() - mouseX) < (width / 2) && (mouseY < (height / 2))) {
                x1 = $(clkEml).width() - (width + 5);
                y1 = 5;
            //$('#pValue').append('##Close to right corner top##');
            }
            else 
                if ((mouseX < (width / 2)) && (($(clkEml).height() - mouseY) < (height / 2))) {
                    x1 = 5;
                    y1 = $(clkEml).height() - (height + 5);
                //$('#pValue').append('##Close to left corner bottom##');
                }
                else 
                    if (($(clkEml).width() - mouseX) < (width / 2) && (($(clkEml).height() - mouseY) < (height / 2))) {
                        x1 = $(clkEml).width() - (width + 5);
                        y1 = $(clkEml).height() - (height + 5);
                    //$('#pValue').append('##Close to right corner bottom##');
                    }
                    else 
                        if (!(mouseX < (width / 2)) && (mouseY < (height / 2))) {
                            x1 = mouseX - (width / 2);
                            y1 = 5;
                        //$('#pValue').append('##Close to top## >>'+clkEml.offsetTop);
                        }
                        else 
                            if (!(mouseX < (width / 2)) && (($(clkEml).height() - mouseY) < (height / 2))) {
                                x1 = mouseX - (width / 2);
                                y1 = $(clkEml).height() - (height + 5);
                            //$('#pValue').append('##Close to bottom## >>'+clkEml.offsetTop);
                            }
                            else 
                                if ((mouseX < (width / 2)) && !(mouseY < (width / 2))) {
                                    x1 = 5;
                                    y1 = mouseY - (height / 2);
                                //$('#pValue').append('##Close to left## >>'+clkEml.offsetTop);
                                }
                                else 
                                    if (($(clkEml).width() - mouseX) < (width / 2)) {
                                        x1 = $(clkEml).width() - (width + 5);
                                        y1 = mouseY - (height / 2);
                                    //$('#pValue').append('##Close to right## >>'+clkEml.offsetTop);
                                    }
                                    else {
                                        x1 = mouseX - (width / 2);
                                        y1 = mouseY - (height / 2);
                                    }
    }
    x2 = x1 + width;
    y2 = y1 + height;
    
    ias.setOptions({
        show: true,
        x1: mouseX - 1,
        y1: mouseY - 1,
        x2: mouseX + 1,
        y2: mouseY + 1
    });
    ias.animateSelection(x1, y1, x2, y2, 500);
}

$.extend($.imgAreaSelect, {
    animate: function(fx){
        var start = fx.elem.start, end = fx.elem.end, now = fx.now, curX1 = Math.round(start.x1 + (end.x1 - start.x1) * now), curY1 = Math.round(start.y1 + (end.y1 - start.y1) * now), curX2 = Math.round(start.x2 + (end.x2 - start.x2) * now), curY2 = Math.round(start.y2 + (end.y2 - start.y2) * now);
        fx.elem.ias.setSelection(curX1, curY1, curX2, curY2);
        fx.elem.ias.update();
        return fx;
    },
    prototype: $.extend($.imgAreaSelect.prototype, {
        animateSelection: function(x1, y1, x2, y2, duration){
            toggleViewBarImg(true, null);
            var fx = $.extend($('<div/>')[0], {
                ias: this,
                start: this.getSelection(),
                end: {
                    x1: x1,
                    y1: y1,
                    x2: x2,
                    y2: y2
                }
            });
            if (!$.imgAreaSelect.fxStepDefault) {
                $.imgAreaSelect.fxStepDefault = $.fx.step._default;
                $.fx.step._default = function(fx){
                    return fx.elem.ias ? $.imgAreaSelect.animate(fx) : $.imgAreaSelect.fxStepDefault(fx);
                };
            }
            $(fx).animate({
                cur: 1
            }, duration, function(){
                ias.changeView();
                var tagBar = $('#tagBar');
                $("#tgBut").attr('disabled', false);
                ias.resetTVB(tagBar, tagBar.offset().left, tagBar.offset().top, tagBar.offset().left, ((ias.imgObj.offset().top + ias.getSelection().y1) - 7), 300, false);
            });
        }
    })
});
function preview(img, selection){
    var scaleX = 100 / (selection.width || 1);
    var scaleY = 100 / (selection.height || 1);
    $('#tagView > img').css({
        width: Math.round(scaleX * $(img).width()) + 'px',
        height: Math.round(scaleY * $(img).height()) + 'px',
        marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
        marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
    });
}

function toggleTag(state){
    $('#tagBar').toggleClass('tagInActive');
    $('#imgCont').toggleClass('picInActive');
    if (state == 'off') {
        resetTagViewBar();
        ias = null;
        $('#actPnl').css({
            'display': 'block'
        });
    }
}

function activateTags(){
    //alert(JSON.encode(tagSets));
    $('#imgCont').crtTagApnd(tagSets);
    $('.tgWin').hover(function(){
        $(this).appTaGNm(tagSets, this.id.charAt(this.id.length - 1));
    }, function(){
        $('.nmTg').remove();
    });
}

function deacivateTags(){
    //iterate tagset and remove
}

function resetTagViewBar(){
    ias.imgObj.unbind('click');
    $('#tagViewButtonBar').html('');
    var actBt = document.createElement('button');
    $(actBt).html('Activate');
    actBt.onmouseup = function(){
        activateTag();
    };
    $gel('tagViewButtonBar').appendChild(actBt);
    toggleViewBarImg(false, 'Tag<br>Photo');
}

function toggleViewBarImg(isImg, msgTxt){
    var tagView = $('#tagView');
    tagView.html('');
    if (isImg) {
        var tagVwCpImg = $(curImg).clone();
        tagVwCpImg.id = 'tagVwCpImg';
        tagView.append(tagVwCpImg);
    }
    else {
        var tagMsg = elemCrt('tagMsg', 'div', null);
        $(tagMsg).html(msgTxt);
        tagView.append(tagMsg);
    }
}

/**
 * A DOM getter function similar to document.getElementById
 */
function $gel(){
    var elements = new Array();
    // Find all the elements supplied as arguments
    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        // If the argument is a string assume it's an id
        if (typeof element == 'string') {
            element = document.getElementById(element);
        }
        // If only one argument was supplied, return the
        // element immediately
        if (arguments.length == 1) {
            return element;
        }
        // Otherwise add it to the array
        elements.push(element);
    }
    // Return the array of multiple requested elements
    return elements;
}

function elemCrt(id, tp, cls){
    var elmc = document.createElement(tp);
    //elmc
    id != null ? elmc.id = id : null;
    cls != null ? elmc.className = cls : null;
    
    return elmc;
}

/**
 * Function to get the size of the browser window
 */
function innerSize(){
    var myWidth = 0, myHeight = 0;
    if (typeof(window.innerWidth) == 'number') {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    }
    else 
        if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
            //IE 6+ in 'standards compliant mode'
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        }
        else 
            if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                //IE 4 compatible
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
            }
    var bSize = {
        'X': myWidth,
        'Y': myHeight
    };
    return bSize;
}

/**
 * function to center element within specified client
 *
 * @param {Object} parent
 * @param {Object} centObj
 */
function centerWN(parent, centObj){
    var pObj = $('#' + parent), cntObj = $('#' + centObj);
    var pcX = (Math.round(pObj.width() / 2)) + pObj.offset().left;
    var pcY = (Math.round(pObj.height() / 2)) + pObj.offset().top;
    $gel(centObj).style.cssText = 'top:' + (pcY - (cntObj.height() / 2)) + 'px; left:' + (pcX - (cntObj.width() / 2)) + 'px';
}

function replaceAll(str, searchTerm, replaceWith, ignoreCase){
    var regex = "/" + searchTerm + "/g";
    if (ignoreCase) 
        regex += "i";
    return str.replace(eval(regex), replaceWith);
}

function shTagBox(width, height, top, left, cnclCallback){
    tgNmSt = [];
    var tgBxslct = elemCrt('tgBxslct', 'div', 'tgBxslct');
    var tagBar = $('#tagBar');
    $(tgBxslct).offset({
        left: tagBar.offset().left,
        top: (tagBar.offset().top + (getScrollXY().y - scrlY + DEF_TAG_MV))
    });
    var nameLb = elemCrt('tgName', 'label', null);
    $(nameLb).html('Type any name:');
    var tgNmInpt = elemCrt('tgNminpt', 'input', 'tgn');
    tgNmInpt.type = 'text';
    tgNmInpt.autocomplete = 'off';
    tgNmInpt.size = 20;
    $(tgNmInpt).keyup(function(event){
        $(tgNmInpt).attr('cntSz', 0);
        if (event.keyCode != 255) {
            $(tgUlst).html('');
            if ($(tgUlst).tgUsropts(usrLst, replaceAll(tgNmInpt.value, "\\\\", "\\\\", true)) == 0) {
                $(tgUlst).css({
                    'display': 'none'
                });
                $('#tagMail').css({
                    'display': 'block'
                });
                $('#blName').html(tgNmInpt.value);
            }
            else {
                $(tgUlst).css({
                    'display': 'block'
                });
                $('#tagMail').css({
                    'display': 'none'
                });
            }
        }
    });
    
    var tgUlstCont = elemCrt(null, 'div', null);
    var psnLb = elemCrt('tgName', 'label', null);
    $(psnLb).html('or choose a person:');
    
    var tgUlst = elemCrt('tgUlst', 'div', null);
    $(tgUlst).tgUsropts(usrLst, null);
    
    var tgBtnPnl = elemCrt('tagbtn', 'div', 'tgBtn');
    $(tgUlstCont).append(psnLb).append(tgUlst);
    
    var tgMail = elemCrt('tagMail', 'div', null);
    var blName = elemCrt('blName', 'span', null);
    $(blName).html('isaac');
    blName.style.fontWeight = 'bold';
    $(tgMail).html('Enter ');
    $(tgMail).append(blName);
    $(tgMail).html($(tgMail).html() + "'s mail to send Tag mail and invite notification");
    var dvc = elemCrt(null, 'div', null);
    var emlBl = elemCrt('emlBl', 'label', null);
    $(emlBl).html('Email:');
    var inptMl = elemCrt('inptMl', 'input', 'inpt');
    $(dvc).append(emlBl);
    $(dvc).append(inptMl);
    $(tgMail).append(dvc);
    $(tgMail).css({
        'display': 'none'
    });
    
    var inptTag = elemCrt('tgBt', 'input', 'inptBt');
    inptTag.type = 'button';
    inptTag.value = 'Tag';
    inptTag.onclick = function(){
        addTag(tagSets, tgNmSt, width, height, top, left);
        cnclCallback();
        $(tgBxslct).children().remove();
        $(tgBxslct).remove();
    };
    var inptCncl = elemCrt('tgCncl', 'input', 'inptBt inptAlt');
    inptCncl.type = 'button';
    inptCncl.value = 'Cancel'
    
    inptCncl.onclick = function(){
        $(tgBxslct).children().remove();
        $(tgBxslct).remove();
        cnclCallback();
    }
    $(tgBtnPnl).append(inptTag).append(inptCncl);
    
    $(tgBxslct).append(nameLb).append(tgNmInpt).append(tgUlstCont).append(tgMail).append(tgBtnPnl);
    document.body.appendChild(tgBxslct);
}

$.fn.tgUsropts = function(data, srch){
    var nfnd = 0;
    var select = this;
    $.each(data, function(index, itemData){
        var lbl = elemCrt(null, 'label', null);
        var input = elemCrt(null, 'input', null);
        input.value = itemData.value;
        input.type = 'checkbox';
        $(input).attr('onclick', 'tgNmClck(' + itemData.value + ', "' + itemData.text + '");');
        $(lbl).append(input);
        $(lbl).html($(lbl).html() + itemData.text);
        if (srch == null) {
            $(select).append(lbl);
            ++nfnd;
        }
        else {
            if (itemData.text.search(new RegExp(srch, 'gi')) >= 0) {
                $(select).append(lbl);
                ++nfnd;
            }
        }
    });
    return nfnd;
}
function tagNmClean(tgJson, name){
    var tempJson = [];
    var found = false;
    $.each(tgJson, function(index, itemData){
        itemData.name == name ? found = true : tempJson[index] = itemData;
    });
    tgNmSt = tempJson;
    return found;
}

function addTag(tagSets, tgNmSt, width, height, top, left){
    tagSets[tagSets.length] = {
        'names': tgNmSt,
        'top': top,
        'left': left,
        'width': width,
        'height': height
    }
}

function tgNmClck(id, name){
    var found = false;
    var curHld = $(this);
    $.each(tgNmSt, function(index, itemData){
        if (itemData.name == name) {
            name.splice(index, 1);
            found = true;
            return false;
        }
    });
    if (!found) {
        tgNmSt[tgNmSt.length] = {
            'id': id,
            'name': name
        }
    }
}

function crtTag(tgId, imgCnt, width, height, top, left){
    var selTag_win = elemCrt('tg_window_' + tgId, 'span', 'tgWin');
    var selTag_in = elemCrt(null, 'span', 'tgIn');
    $(selTag_in).width(width);
    $(selTag_in).height(height);
    selTag_win.style.left = left + 'px';
    selTag_win.style.top = top + 'px';
    $(selTag_win).append(selTag_in);
    $(imgCnt).append(selTag_win);
}

$.fn.crtTagApnd = function(data){
    return this.each(function(){
        var select = this;
        $.each(data, function(index, itemData){
            crtTag(index, select, itemData.width, itemData.height, itemData.top, itemData.left);
        });
    });
}
function getScrollXY(){
    var scrOfX = 0, scrOfY = 0;
    if (typeof(window.pageYOffset) == 'number') {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    }
    else 
        if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
            //DOM compliant
            scrOfY = document.body.scrollTop;
            scrOfX = document.body.scrollLeft;
        }
        else 
            if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
                //IE6 standards compliant mode
                scrOfY = document.documentElement.scrollTop;
                scrOfX = document.documentElement.scrollLeft;
            }
    return {
        x: scrOfX,
        y: scrOfY
    };
}

$.fn.appendThumbImages = function(data){
    return this.each(function(){
        var select = this;
        $.each(data, function(index, itemData){
            var cnt = elemCrt(null, 'a', 'pic');
            var imgEl = elemCrt(null, 'img', 'thView');
            ((itemData.width > itemData.height) && (itemData.height < 90)) ? $(imgEl).addClass('thViewHoz') : null;
            imgEl.src = DEFAULT_GEN_LINK + itemData.name;
            $(cnt).click(function(){
                loadImage('imgCont', DEFAULT_SEC_LINK + itemData.url, function(){
                
                });
            }, 2000);
            $(cnt).append(imgEl);
            $(select).append(cnt);
        });
    });
}
function togglethView(sts){
    var $mvp = $('#miniPV');
    if (!sts) {
        miniPvOpen = false;
        $mvp.stop(true, true).animate({
            'bottom': '-130px'
        }, 300);
    }
    else {
        miniPvOpen = true;
        $mvp.stop(true, true).animate({
            'bottom': '0px'
        }, 400);
    }
}

$.fn.appTaGNm = function(data, id){
    var select = this;
    $.each(data[id].names, function(index, itemData){
        var nmTg = elemCrt(null, 'span', 'nmTg');
        $(nmTg).html(itemData.name);
        document.body.appendChild(nmTg);
        $(nmTg).offset({
            top: data[id].top + data[id].height,
            left: (data[id].left + (Math.round(data[id].width / 2))) - (Math.round($(nmTg).width() / 2))
        });
        
    });
}
function jgt(url, dataKey, act){
    $.ajaxSetup({
        scriptCharset: "utf-8",
        contentType: "application/json; charset=utf-8"
    });
    $.getJSON(url, {
        action: act,
		dataKey: dataKey
    }, function(servData){
        callBack(servData);
    });
}
